package com.example.wechat.login.utils;

import org.redisson.api.RBucket;
import org.redisson.api.RedissonClient;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.concurrent.TimeUnit;

/**
 * 幂等性工具类
 */
@Component
public class IdempotentUtils {

    @Resource
    private RedissonClient redissonClient;

    /**
     * 检查用户是否可以访问
     * @param userId 用户ID
     * @return 是否可以访问
     */
    public boolean canAccess(String userId) {
        String key = "idempotent:user:" + userId;
        RBucket<Long> bucket = redissonClient.getBucket(key);
        long currentTime = System.currentTimeMillis();
        if (bucket.get() == null) {
            bucket.set(currentTime, 2, TimeUnit.SECONDS);
            return true;
        } else {
            long lastAccessTime = bucket.get();
            if (currentTime - lastAccessTime >= 2000) {
                bucket.set(currentTime, 2, TimeUnit.SECONDS);
                return true;
            }
            return false;
        }
    }
}